# -*- coding:utf-8 -*-

"""
  @brief Dump SentiWordNet via Japanese WordNet
  @author Shintaro Takemura(stakemura@gmail.com)
 
  This code is public domain, no warranty expressed or implied, 
  Functionality is thought to be correct, but it's up to you to make
  sure it does what you want.
"""

import os
import sqlite3
from decimal import Decimal

# Open SQLite3 DB
def openSQLite3DB(file_path):
    db = sqlite3.connect(
        os.path.join(os.path.dirname(__file__), file_path),
        detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES )
    db.row_factory = sqlite3.Row
    return db

def main():
    from optparse import OptionParser

    parser = OptionParser()

    parser.add_option("-l", "--limit", dest="limit",
      default=50, type="int",
      help="limit of records", metavar="NUM")
    parser.add_option("-o", "--order", dest="order",
      default='positive',
      help="sort order (postive or negative)" )

    parser.add_option("-y", "--synset", dest="synset",
#      default="01586752-a",
      help="dump based on synset (e.g. 01586752-a)")
    parser.add_option("-w", "--word", dest="word",
      default="good",
      help="dump based on word (e.g. good)")
    parser.add_option("-p", "--pos", dest="pos",
#      default="a",
      help="dump based on part-of-speech (e.g. a)")

    parser.add_option("-d", "--dict", dest="dict",
      default="./wnjpn.db",
      help="Japanese WordNet", metavar="FILE")
    parser.add_option("-s", "--senti", dest="senti",
      default="./SentiWordNet_3.0.0_20100908.sqlite",
      help="SentiWordNet SQLite3 file", metavar="FILE")
        
    options, args = parser.parse_args()

    try:
        sentiWN = openSQLite3DB(options.senti)
        jpWN = openSQLite3DB(options.dict)
        
        results = []
        
        if options.synset:
            cur_pn = sentiWN.execute("select * from synset_pn where synset=?",(options.synset,))
            pn = cur_pn.fetchone()
            cur_pn.close()
            
            cur_sense = jpWN.execute("select * from sense where synset=? order by freq desc",(options.synset,))
            for sense in cur_sense.fetchall():
                result = []
                result.append(sense["synset"])
                result.append(str(Decimal(pn['positive'])/Decimal(8)))
                result.append(str(Decimal(pn['negative'])/Decimal(8)))
                pos = options.synset[-1:]
                
                cur_word = jpWN.execute("select * from word where wordid=? and pos=?", (sense["wordid"],pos))
                word = cur_word.fetchone()
                if word:
                    result.append(word['lemma'])
                cur_word.close()

                cur_synset_ex = jpWN.execute("select * from synset_ex where synset=? and lang=?", (sense["synset"],word['lang']))
                synset_ex = cur_synset_ex.fetchone()
                if synset_ex:
                    result.append(synset_ex['def'])
                cur_synset_ex.close()
                
                results.append(result)

            cur_sense.close()

        if options.word:
            cur_sense = jpWN.execute("select sense.synset,sense.lexid from word,sense where sense.wordid=word.wordid and word.lemma=?", (options.word,))
            for sense in cur_sense.fetchall():
                cur_pn = sentiWN.execute("select * from synset_pn where synset=?",(sense['synset'],))
                for pn in cur_pn.fetchall():
                    result = []
                    result.append(sense["synset"])
                    result.append(str(Decimal(pn['positive'])/Decimal(8)))
                    result.append(str(Decimal(pn['negative'])/Decimal(8)))
                    result.append(options.word)
                    result.append(str(sense['lexid']))
                    results.append(result)
                cur_pn.close()
            cur_sense.close()

        if options.pos:
            cur_pn = sentiWN.execute("select * from synset_pn where substr(synset,10,1)=? order by " + options.order + " desc limit ?", (options.pos, options.limit))
            for pn in cur_pn.fetchall():
                cur_sense = jpWN.execute("select * from sense where synset=? order by freq desc",(pn['synset'],))

                result = []
                result.append(pn['synset'])
                result.append(str(Decimal(pn['positive'])/Decimal(8)))
                result.append(str(Decimal(pn['negative'])/Decimal(8)))

                for sense in cur_sense.fetchall():
                    pos = sense["synset"][-1:]
                    
                    cur_word = jpWN.execute("select * from word where wordid=? and pos=?", (sense["wordid"],pos))
                    word = cur_word.fetchone()
                    if word:
                        result.append(word['lemma'])
                    cur_word.close()
                
                cur_sense.close()
                results.append(result)
                
        for result in results:
            print(",".join(result))
        
        jpWN.close()        
        sentiWN.close()
        
    except IOError, (errno, msg):
        print('except: Cannot open "%s"' % options.input)
        print('  errno: [%d] msg: [%s]' % (errno, msg))

if __name__ == "__main__":
    main()